<template>
  <div>
    <myDivider name="租赁管理"></myDivider>
    <div class="Top">
      <div style="display: flex;">

        <el-input style="width: 160px;" v-model="key1" placeholder="根据小区名称搜索" @keyup.enter.native="getTableList"
          clearable></el-input>

        <el-input style="width: 150px;margin-left: 15px;" v-model="key2" placeholder="根据车位号搜索"
          @keyup.enter.native="SouSuo" clearable></el-input>
        <el-input style="width: 180px;margin-left: 15px;" v-model="key3" placeholder="根据归属人姓名搜索"
          @keyup.enter.native="SouSuo" clearable></el-input>
        <el-input style="width: 180px;margin-left: 15px;" v-model="key4" placeholder="根据租赁人姓名搜索"
          @keyup.enter.native="SouSuo" clearable></el-input>

        <el-date-picker style="width: 250px;margin-left: 20px;" @change="SouSuo" value-format="yyyy-MM-dd"
          v-model="keyTime" type="daterange" range-separator=" " start-placeholder="创建时间" end-placeholder="请选择时间段">
        </el-date-picker>

        <el-button type="primary" style=" margin-left: 15px" @click="SouSuo">查询</el-button>
        <el-button style="margin-left: 15px" @click="reset">重置</el-button>
      </div>
      <el-button style="margin-top: 10px;" type="primary" @click="addClick">新增</el-button>

    </div>
    <el-table class="tableBox" :data="TableData" style="width: 100%">
      <el-table-column align="center" prop="residentialName" label="小区名称" width="150px">
      </el-table-column>
      <el-table-column align="center" prop="name" label="车位照片" width="100px">
        <template slot-scope="scope">
          <el-image v-if="scope.row.pictureUrl" style="width: 80px; height: 60px" :src="scope.row.pictureUrl"
            :preview-src-list="[scope.row.pictureUrl]">
          </el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="code" label="车位号" width="100px">
      </el-table-column>
      <el-table-column align="center" prop="belongUserName" label="归属人" width="90px">
      </el-table-column>
      <el-table-column align="center" prop="belongUserPhone" label="联系电话" width="150px">
      </el-table-column>
      <el-table-column align="center" prop="tenantUserName" label="租赁人" width="90px">
      </el-table-column>
      <el-table-column align="center" prop="tenantUserPhone" label="联系电话" width="150px">
      </el-table-column>
      <el-table-column align="center" prop="amount" label="金额" width="100px">
      </el-table-column>
      <el-table-column align="center" prop="leaseTerm" label="租赁期限" width="250px">
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="200px">
      </el-table-column>
      <el-table-column align="center" prop="operatorName" label="最后修改人员" width="200px">
      </el-table-column>
      <el-table-column align="center" prop="remarks" label="备注">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.remarks" placement="top-start">
            <span>{{ scope.row.remarks == null || scope.row.remarks == '' ? '—' :
              scope.row.remarks.length > 7 ?
                "..." + scope.row.remarks.substring(scope.row.remarks.length - 7,
                  scope.row.remarks.length) : scope.row.remarks }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px" fixed="right">
        <template slot-scope="scope">
          <div class="textBtn">
            <el-row v-if="scope.row.isRelieve != 1">
              <el-col class="el" :span="6">
                <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="updateClick(scope.row)">编辑</span>
              </el-col>
              <el-col class="el" :span="9">
                <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="fileClick(scope.row)">合同附件</span>
              </el-col>
              <el-col class="el" :span="9">
                <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                  @click="unbindClick(scope.row)">解除租约</span>
              </el-col>
            </el-row>
            <el-row v-else>
              <el-col class="el" :span="24">
                <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="DetailClick(scope.row)">详情</span>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
    </el-table>


    <!-- 新增租赁弹窗 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="550px"
      :title="mainPopType == 'add' ? '新增租赁信息' : mainPopType == 'update' ? '修改租赁信息' : '租赁信息详情'"
      :visible.sync="mainPopShow">
      <el-divider></el-divider>

      <el-form :model="mainForm" :rules="rules" ref="mainForm" label-width="150px">
        <el-form-item label="选择小区：" prop="residentialName" required>
          <div style="display: flex;">
            <el-button @click="toSelect('小区')"
              :disabled="mainPopType == 'update' || mainPopType == 'detail'">选择</el-button>
            <el-input style="width: 230px;" v-model="mainForm.residentialName" disabled
              placeholder="请选择所属小区"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="选择车位：" prop="carSpaceName" required>
          <div style="display: flex;">
            <el-button @click="toSelect('车位')"
              :disabled="mainPopType == 'update' || mainPopType == 'detail'">选择</el-button>
            <el-input style="width: 230px;" v-model="mainForm.carSpaceName" disabled placeholder="请选择车位"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="归属人：" prop="ownerName" required>
          <el-input disabled style="width: 300px;" v-model="mainForm.ownerName" maxlength="20"
            placeholder="请输入归属人"></el-input>
        </el-form-item>
        <el-form-item label="租赁人：" prop="tenantUserName" required>
          <div style="display: flex;">
            <el-button @click="toSelect('租赁人')"
              :disabled="mainPopType == 'update' || mainPopType == 'detail'">选择</el-button>
            <el-input style="width: 230px;" v-model="mainForm.tenantUserName" disabled placeholder="请选择租赁人"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="金额：">
          <el-input style="width: 300px;" v-model="mainForm.amount" type="number" maxlength="10"
            :disabled="mainPopType == 'detail'" placeholder="请输入金额"></el-input>
        </el-form-item>

        <el-form-item label="使用期限" prop="time">
          <el-date-picker :picker-options="pickerOptions" style="width: 300px;" v-model="mainForm.time" type="daterange"
            range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
            :disabled="mainPopType == 'detail'">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="合同：">
          <!-- 新增和修改展示上传文件 -->
          <MyUploadFileNotDetele :canUploadNum="5" v-if="MyUploadFileNotDeteleShow && mainPopType != 'detail'"
            @deleteFileList="deleteFileList" @getFileList="getFileList" :id="uploadId" :EchoFileList="EchoFileList"
            uploadUrl="/business/parkingSpaceRent/uploadAnnex">
          </MyUploadFileNotDetele>
          <!-- 详情只展示文件 -->
          <div v-if="mainPopType == 'detail'" style="width: 300px;">

            <div v-if="contractPopData.length > 0">
              <div class="el" v-for="item, i in contractPopData" :key="i"
                style="display: flex;justify-content: space-between;width: 100%;">
                <span>
                  {{ item.name }}
                </span>
                <div>
                  <el-button size="mini" type="primary" icon="el-icon-download" @click="dow(item)"></el-button>
                </div>
              </div>
            </div>
            <span v-else style="color: #aaa">暂无合同附件</span>
          </div>
          <!-- 定位 -->
        </el-form-item>
        <el-form-item label="备注：">
          <el-input style="width: 300px;" rows="4" v-model="mainForm.remarks" type="textarea" maxlength="200"
            show-word-limit placeholder="请输入" :disabled="mainPopType == 'detail'"></el-input>

        </el-form-item>
      </el-form>

      <el-divider></el-divider>
      <div v-if="mainPopType != 'detail'" slot="footer"
        style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="mainPopShow = false">取 消</el-button>
        <el-button type="primary" @click="mainPopOk">确
          定</el-button>
      </div>

    </el-dialog>





    <!-- 选择弹窗 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="800px" :title="'选择' + selectType"
      :visible.sync="selectShow">
      <el-divider v-if="selectType != '车位'"></el-divider>
      <el-tabs v-if="selectType == '车位'" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="新增租赁" name="lease"></el-tab-pane>
        <el-tab-pane label="车位续租" name="Renewal"></el-tab-pane>
      </el-tabs>

      <!-- 筛选项 -->
      <!-- 筛选项 -->
      <!-- 筛选项 -->
      <div v-if="selectType == '小区'" style="display: flex;justify-content: space-between;margin: 20px 0;">
        <el-cascader change-on-select style="width: 300px;" clearable v-model="selectPopKeyArea"
          @change="cascaderChange" :props="props" placeholder="请选择地区"></el-cascader>
        <el-input @keyup.enter.native="popSouSuo" size="medium" style="width: 300px;"
          v-model="selectPopKeyResidentialName" placeholder="输入小区名称搜索"></el-input>
        <el-button size="medium" type="primary" @click="popSouSuo">查询</el-button>
      </div>

      <div v-if="selectType == '车位'" style="display: flex;justify-content: space-between;margin: 20px 0;">
        <el-input @keyup.enter.native="popSouSuo" size="medium" style="width: 300px;"
          v-model="selectPopKeycarSpaceNumber" placeholder="输入车位号搜索"></el-input>
        <el-button size="medium" type="primary" @click="popSouSuo">查询</el-button>
      </div>

      <div v-if="selectType == '租赁人'" style="display: flex;justify-content: space-between;margin: 20px 0;">
        <el-input @keyup.enter.native="popSouSuo" size="medium" style="width: 300px;" v-model="selectPopKeyName"
          placeholder="输入用户姓名搜索"></el-input>
        <el-input @keyup.enter.native="popSouSuo" size="medium" style="width: 300px;" v-model="selectPopKeyPhone"
          placeholder="输入手机号码搜索"></el-input>
        <el-button size="medium" type="primary" @click="popSouSuo">查询</el-button>
      </div>
      <!-- 表格 --> <!-- 表格 --> <!-- 表格 --> <!-- 表格 -->
      <div class="popTableStyle">
        <el-table ref="selectTable" :data="selectData" style="width: 100%" height="300px" highlight-current-row>

          <el-table-column v-if="selectType == '小区'" align="center" prop="areaName" label="地区">
          </el-table-column>
          <el-table-column v-if="selectType == '小区'" align="center" prop="name" label="小区名称">
            <!-- <template slot-scope="scope">
              {{ scope.row.unitType == 'agency' ? '机关' : scope.row.unitType
        == 'company' ? '机构' : '系统' }}
            </template> -->
          </el-table-column>

          <el-table-column v-if="selectType == '车位'" align="center" prop="pictureUrl" label="车位照片">
            <template slot-scope="scope">
              <el-image v-if="scope.row.pictureUrl" style="width: 80px; height: 60px" :src="scope.row.pictureUrl"
                :preview-src-list="[...scope.row.pictureUrl]">
              </el-image>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column v-if="selectType == '车位'" align="center" prop="code" label="车位号">
          </el-table-column>


          <el-table-column v-if="selectType == '租赁人'" align="center" prop="customerName" label="用户姓名">
          </el-table-column>
          <el-table-column v-if="selectType == '租赁人'" align="center" prop="phone" label="手机号码">
          </el-table-column>
        </el-table>
      </div>
      <myPagination v-if="selectType == '车位' || selectType == '租赁人'" :pageNum="popPageNum" :total="popTotal"
        @PageChange="popPageChange" @pageSizeChange="popPageSizeChange">
      </myPagination>
      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="selectShow = false">取 消</el-button>
        <el-button type="primary" @click="selectOk">确
          定</el-button>
      </div>

    </el-dialog>

    <!-- 合同附件 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="600px" title="合同附件"
      :visible.sync="annexPopShow">
      <el-divider></el-divider>
      <el-upload style="margin: 10px 0;" action="" :before-upload="beforeUpload" multiple :limit="5"
        :show-file-list="false" :http-request="uploadRes">
        <el-button size="small" type="primary">上传附件</el-button>
      </el-upload>
      <el-table :data="AnnexTableData" height="300px" style="width: 100%">
        <el-table-column align="center" prop="annexName" label="附件名称">
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="上传时间">
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <div class="textBtn">
              <el-row>
                <el-col class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="previewClick(scope.row)">预览</span>
                </el-col>
                <el-col class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="dowClick(scope.row)">下载</span>
                </el-col>
                <el-col class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="deleteClick(scope.row)">删除</span>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-divider></el-divider>


    </el-dialog>
    <!-- 分页器 -->
    <myPagination :pageNum="pageNum" :total="totalSize" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>
  </div>
</template>





<script>
import MyUploadFileNotDetele from '@/components/upload/MyUploadFileNotDetele'
import axios from 'axios'
import { encode } from "js-base64";
export default {
  components: {
    MyUploadFileNotDetele
  },
  data() {
    return {
      popPageNum: 1,
      popPageSize: 10,
      popTotal: 0,
      // 顶部筛选 ===================
      key1: '',
      key2: '',
      key3: '',
      key4: '',
      keyTime: ['', ''],
      //===================  顶部筛选

      // 主要表格==================
      TableData: [{ name: '1', img: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg' }], //用户数据
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      // ==================主要表格

      // 主要弹窗 =============================
      mainForm: {},
      rules: {
        residentialName: [
          { required: true, message: '归属小区不能为空', trigger: 'blur' }
        ],
        carSpaceName: [
          { required: true, message: '归属车位不能为空', trigger: 'blur' }
        ],
        ownerName: [
          { required: true, message: '归属人不能为空', trigger: 'blur' }
        ],
        tenantUserName: [
          { required: true, message: '租赁人能为空', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择期限', trigger: 'change' }
        ],

      },
      mainPopType: '',
      mainPopShow: false,
      // 附件相关
      uploadId: null,
      deleteFile: [],
      MyUploadFileNotDeteleShow: false,
      EchoFileList: [],
      contractPopData: [],
      minTime: '',
      pickerOptions: {
        disabledDate: (time) => {
          if (this.minTime) {
            return time.getTime() < new Date(this.minTime);
          } else {
            return time.getTime() < new Date();
          }

        }
      },
      // ==============================主要弹窗



      // 选择弹窗=======================
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          if (node.level == 0) {
            let { level } = node;
            this.$api.car.myGetcityList("000000").then(res => {
              res.data.forEach(el => {
                el.value = el.criCode;
                el.label = el.criName;
                el.leaf = level >= 3;
              });
              resolve(res.data);
            });
          } else {

            let { level } = node;
            this.$api.car.myGetcityList(node.value).then(res => {
              res.data.forEach(el => {
                el.value = el.criCode;
                el.label = el.criName;
                el.leaf = level >= 3;
              });
              resolve(res.data);
            });
          }

        }
      },
      selectPopKeyArea: [],
      selectPopKeyResidentialName: '',
      selectPopKeycarSpaceNumber: '',
      selectPopKeyName: '',
      selectPopKeyPhone: '',
      selectShow: false,
      selectType: '',
      selectData: [{ unitName: '5', id: 5 }, { unitName: '1', id: 1 }],
      // ===========================选择车位
      activeName: 'lease',

      // 合同附件弹窗====================
      AnnexTableData: [],
      detailData: {},
      fileUrlList: [],
      annexPopShow: false,
      activeRow: {},
      // =============================合同附件弹窗



    };
  },
  async activated() {
    this.reset() // 重置清空 然后查询列表
  },
  methods: {
    popSouSuo() {
      this.popPageNum = 1
      this.popPageSize = 10
      this.getSelectPopData()
    },
    popPageChange(e) { //选择弹窗分页器
      this.popPageNum = e
      this.getSelectPopData()
    },
    popPageSizeChange(e) {//选择弹窗分页器
      this.popPageNum = 1
      this.popPageSize = e
      this.getSelectPopData()
    },
    //合同附件=================
    previewClick(row) {
      console.log(row, 'dwqdq')
      let url = defaultUrl + '/annex/' + row.annexUrl; //要预览文件的访问地址
      window.open('http://preview.quich.com.cn/onlinePreview?url=' + encodeURIComponent(encode(url)));
    },
    dowClick(row) {
      console.log(row);
      let soa_account = sessionStorage.getItem("soa_account");
      const token = sessionStorage.getItem("soa_token")
      axios({
        method: 'get',
        url: defaultUrl + `/business/parkingSpaceRent/downloadAnnex?filename=${row.annexUrl}`,
        headers: {
          // 在这里添加自己需要的请求头
          account: soa_account,
          token: token,
        },
        responseType: 'blob'
      }).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const a = document.createElement('a')
        a.href = url
        a.setAttribute('download', row.annexName)
        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)
      })

    },
    async deleteClick(row) {
      this.$confirm('此操作将永久删除该附件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        this.fileUrlList.forEach(async (el, i) => {
          if (el == row.annexUrl) {
            let res = await this.$api.ImgFile.delete(defaultUrl + '/business/parkingSpaceRent/deleteAnnex', {
              "filename": this.fileUrlList[i]
            })
            this.fileUrlList.splice(i, 1)

            // 走修改接口，只修改附件字段
            let { id, amount, tenantTermStart, tenantTermEnd, remarks } = this.detailData
            let res1 = await this.$api.car.myParkingSpaceRentUpdate({
              id, amount, tenantTermStart, tenantTermEnd, remarks,
              contractUrlArray: this.fileUrlList
            })
            if (res1.code == 200) {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getDetail()
            } else {
              this.$message.error(res1.message)
            }
          }
        })

      }).catch(() => {

      });

    },
    async getDetail() {
      let res = await this.$api.car.myParkingSpaceRentDetail(this.activeRow.id)
      console.log(res.data, '详情的');
      if (res.code == 200) {
        // 复制一份详情，用来修改用
        this.detailData = res.data

        if (res.data.contractUrl) {
          this.AnnexTableData = JSON.parse(res.data.contractUrl)
          let arr = []
          if (res.data.contractUrl) {
            JSON.parse(res.data.contractUrl).forEach(el => {
              arr.push(el.annexUrl)
            })
          }
          this.fileUrlList = arr
        }

      } else {
        this.$message.error(res.message)
      }
    },
    beforeUpload(file) {
      // 判断是否含有特殊字符
      var pattern = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/; // 定义特殊字符的正则表达式模式
      if (pattern.test(file.name)) {
        this.$message.error('文件名称含有特殊字符,请修改后上传');
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        this.$message.error('附件大小不能超过 1MB!');
      }
      return isLt2M;
    },
    async uploadRes(e) {
      let formData = new FormData()
      formData.append('files', e.file)// 传文件
      formData.append('id', this.activeRow.id)// 传文件
      let res = await this.$api.ImgFile.upload(defaultUrl + '/business/parkingSpaceRent/uploadAnnex', formData)
      if (res.data.code == 200) {
        // 上传附件之后，
        this.fileUrlList.push(res.data.data[0])
        // 走修改接口，只修改附件字段
        let { id, amount, tenantTermStart, tenantTermEnd, remarks } = this.detailData
        let res1 = await this.$api.car.myParkingSpaceRentUpdate({
          id, amount, tenantTermStart, tenantTermEnd, remarks,
          contractUrlArray: this.fileUrlList
        })
        if (res1.code == 200) {
          this.$message({
            message: '上传成功',
            type: 'success'
          });
          this.getDetail()
        } else {
          this.$message.error(res1.message)
        }
      } else {
        this.$message.error('上传失败');
        this.clear()
      }
    },
    // ====================合同附件
    // 主要按钮 ===============================================================

    addClick() {
      // 选择框的搜索条件清空
      this.selectPopKeyArea = []
      this.selectPopKeyResidentialName = ''
      this.selectPopKeycarSpaceNumber = ''
      this.selectPopKeyName = ''
      this.selectPopKeyPhone = ''
      // 清空内容
      {
        this.$set(this.mainForm, 'id', 0)
        this.$set(this.mainForm, 'residentialId', '')
        this.$set(this.mainForm, 'residentialName', '')
        this.$set(this.mainForm, 'spaceId', '')
        this.$set(this.mainForm, 'carSpaceName', '')
        this.$set(this.mainForm, 'ownerName', '')
        this.$set(this.mainForm, 'tenantUserId', '')
        this.$set(this.mainForm, 'tenantUserName', '')
        this.$set(this.mainForm, 'amount', '')
        this.$set(this.mainForm, 'remarks', '')
        this.$set(this.mainForm, 'contractUrlArray', [])
        this.$set(this.mainForm, 'time', [])
        this.$set(this.mainForm, 'tenantTermStart', '')
        this.$set(this.mainForm, 'tenantTermEnd', '')
        this.activeName = 'lease'
        // 处理附件
        this.MyUploadFileNotDeteleShow = false
        this.uploadId = 0
        this.deleteFile = []
        this.EchoFileList = []
        setTimeout(() => {
          this.MyUploadFileNotDeteleShow = true
        }, 50)

        this.$nextTick(() => {
          this.$refs.mainForm.clearValidate()
        })
      }

      this.mainPopType = 'add'
      this.mainPopShow = true
    },
    async updateClick(row) {
      console.log('修改点击了', row);
      let res = await this.$api.car.myParkingSpaceRentDetail(row.id)
      console.log(res.data, '详情的');
      if (res.code == 200) {
        this.$set(this.mainForm, 'id', res.data.id)
        this.$set(this.mainForm, 'residentialId', res.data.residentialId)
        this.$set(this.mainForm, 'residentialName', res.data.residentialName)
        this.$set(this.mainForm, 'spaceId', res.data.spaceId)
        this.$set(this.mainForm, 'carSpaceName', res.data.code)
        this.$set(this.mainForm, 'ownerName', res.data.belongUserName)
        this.$set(this.mainForm, 'tenantUserId', res.data.tenantUserId)
        this.$set(this.mainForm, 'tenantUserName', res.data.tenantUserName)
        this.$set(this.mainForm, 'amount', res.data.amount)
        this.$set(this.mainForm, 'remarks', res.data.remarks)
        let arr = []
        if (res.data.contractUrl) {
          JSON.parse(res.data.contractUrl).forEach(el => {
            arr.push(el.annexUrl)
          })
        }

        this.$set(this.mainForm, 'contractUrlArray', arr)

        this.$set(this.mainForm, 'tenantTermStart', res.data.tenantTermStart)
        this.$set(this.mainForm, 'tenantTermEnd', res.data.tenantTermEnd)
        if (res.data.tenantTermStart && res.data.tenantTermEnd) {
          this.$set(this.mainForm, 'time', [res.data.tenantTermStart, res.data.tenantTermEnd])
        }
        this.activeName = 'lease'
        // 处理附件
        this.MyUploadFileNotDeteleShow = false
        this.uploadId = res.data.id
        this.deleteFile = []
        this.EchoFileList = arr
        setTimeout(() => {
          this.MyUploadFileNotDeteleShow = true
        }, 50)
      } else {
        this.$message.error(res.message)
      }
      this.mainPopType = 'update'
      this.mainPopShow = true
    },
    fileClick(row) {
      this.annexPopShow = true
      this.activeRow = row
      this.getDetail()
      // this.$router.push(`/car/carSpaceLeaseAnnex?id=${row.id}`)
      // console.log('合同附件点击了', row);
      // if(!row.contractUrlArray){
      //   this.$message.error('暂无附件')
      //   return
      // }
      // this.contractPopShow = true
      // this.contractPopData = []
      // row.contractUrlArray.forEach(el => {
      //   let lastIndex = el.lastIndexOf('/');
      //   this.contractPopData.push({
      //     name: el.slice(lastIndex + 1),
      //     url: el
      //   })
      // })
    },
    async DetailClick(row) {
      console.log('详情点击了', row);
      let res = await this.$api.car.myParkingSpaceRentDetail(row.id)

      if (res.code == 200) {
        // 展示附件列表===========
        this.contractPopData = []
        if (res.data.contractUrl) {
          JSON.parse(res.data.contractUrl).forEach(el => {

            let lastIndex = el.annexUrl.lastIndexOf('/');
            this.contractPopData.push({
              name: el.annexUrl.slice(lastIndex + 1),
              url: el.annexUrl
            })
          })
        }
        console.log(this.contractPopData, '详情的');
        // ==================展示附件列表
        this.$set(this.mainForm, 'residentialName', res.data.residentialName)
        this.$set(this.mainForm, 'carSpaceName', res.data.code)
        this.$set(this.mainForm, 'ownerName', res.data.belongUserName)
        this.$set(this.mainForm, 'tenantUserName', res.data.tenantUserName)
        this.$set(this.mainForm, 'amount', res.data.amount)
        this.$set(this.mainForm, 'remarks', res.data.remarks)
        if (res.data.tenantTermStart && res.data.tenantTermEnd) {
          this.$set(this.mainForm, 'time', [res.data.tenantTermStart, res.data.tenantTermEnd])
        }
      } else {
        this.$message.error(res.message)
      }
      this.mainPopType = 'detail'
      this.mainPopShow = true
    },
    unbindClick(row) {
      this.$confirm('此操作将会解除租约, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        console.log('删除点击了', row);
        let res = await this.$api.car.myRelieveParkingSpaceRent(row.id)
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '解绑成功!'
          });
          this.getTableList()
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {

      });

    },
    //======================================================================主要按钮

    // 主要弹窗 =============================
    toSelect(val) { //val 小区 车位  租赁人
      this.selectType = val
      this.popPageNum = 1
      this.popPageSize = 10
      switch (val) {
        case '小区':

          break;

        case '车位':
          if (!this.mainForm.residentialId) {
            this.$message.error('请您先选择小区')
            return
          }
          break;
        case '租赁人':

          break;
      }
      this.getSelectPopData()
      this.selectShow = true
    },
    cascaderChange() {
      this.$nextTick(() => {
        this.popPageNum = 1
        this.popPageSize = 10
        this.getSelectPopData()
        const dom = document.getElementsByClassName("el-radio is-checked")[0];
        if (dom == undefined) return
        const brother = dom.nextElementSibling;
        brother.click();

      });
    },
    getSelectPopData() { //获取选择列表
      //获取表格数据 selectData
      if (this.selectType == '小区') {
        this.getCommunityData()//获取社区列表
      }
      else if (this.selectType == '车位') {
        this.getCarSpaceData()
      }
      else if (this.selectType == '租赁人') {
        this.getTenantData()
      }
    },
    async getCommunityData() { //获取社区列表
      let params = {
        "provinceCode": this.selectPopKeyArea[0], //省代号
        "cityCode": this.selectPopKeyArea[1], //市代号
        "districtCode": this.selectPopKeyArea[2], //区代号
        "streetCode": this.selectPopKeyArea[3], //街道代号
        "residentialName": this.selectPopKeyResidentialName //小区名
      }
      let res = await this.$api.car.myGetResidentialList(params)
      if (res.code == 200) {
        this.selectData = res.data
      } else {
        this.$message.error(res.message)
      }
      this.selectData.forEach((el, i) => {
        if (el.residentialId == this.mainForm.residentialId) {
          this.$nextTick(() => {
            this.$refs.selectTable.setCurrentRow(this.selectData[i])
          })
        }
      })
    },
    async getCarSpaceData() { //获取车位列表
      let status
      switch (this.activeName) {
        case 'lease':
          status = 0
          break
        case 'Renewal':
          status = 1
          break
      }
      let params = {
        "residentialId": this.mainForm.residentialId, //小区id 必填
        "code": this.selectPopKeycarSpaceNumber, //车位号
        "status": status, //租赁状态 0:未出租 1:已出租
        pageNum: this.popPageNum,
        pageSize: this.popPageSize,
      }
      let res = await this.$api.car.myGetSpaceListByResidentialId(params)
      if (res.code == 200) {
        if (res.data.list.length == 0 && this.popPageNum != 1) {
          this.popPageNum = 1
          this.getCarSpaceData()
          return
        }
        this.selectData = res.data.list
        this.popTotal = res.data.total
        this.selectData.forEach((el, i) => {
          if (el.spaceId == this.mainForm.spaceId) {
            this.$nextTick(() => {
              this.$refs.selectTable.setCurrentRow(this.selectData[i])
            })
          }
        })
      } else {
        this.$message.error(res.message)
      }
    },
    async getTenantData() { //获取租赁人列表
      let res = await this.$api.car.myGetCustomerList({
        "name": this.selectPopKeyName, //姓名
        "phoneNumber": this.selectPopKeyPhone, //手机号
        "idNumber": "", //身份证号
        "pageSize": this.popPageSize,
        "pageNum": this.popPageNum
      })

      if (res.code == 200) {
        if (res.data.list.length == 0 && this.popPageNum != 1) {
          this.popPageNum = 1
          this.getTenantData()
          return
        }
        this.selectData = res.data.list
        this.popTotal = res.data.total
      } else {
        this.$message.error(res.message)
      }
      this.selectData.forEach((el, i) => {
        if (el.belongUserId == this.mainForm.tenantUserId) {
          this.$nextTick(() => {
            this.$refs.selectTable.setCurrentRow(this.selectData[i])
          })
        }
      })
    },
    mainPopOk() {
      this.$refs['mainForm'].validate((valid) => {
        if (valid) {

          this.$confirm('是否提交?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            // 时间转换
            this.$set(this.mainForm, 'tenantTermStart', this.mainForm.time[0])
            this.$set(this.mainForm, 'tenantTermEnd', this.mainForm.time[1])
            // 附件删除
            this.deleteFile.forEach(async (el) => {
              let res = await this.$api.ImgFile.delete(defaultUrl + '/business/parkingSpaceRent/deleteAnnex', {
                "filename": el
              })
            })

            let { residentialId, spaceId, tenantUserId, amount, tenantTermStart, tenantTermEnd, contractUrlArray, remarks, id } = this.mainForm
            if (this.mainPopType == 'add') {
              let params = { residentialId, spaceId, tenantUserId, amount, tenantTermStart, tenantTermEnd, contractUrlArray, remarks }
              let res = await this.$api.car.myParkingSpaceRentInsert(params)
              console.log(res, '新增');
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                });
                this.getTableList()
                this.mainPopShow = false
              } else {
                this.$message.error(res.message)
              }
            } else { //如果是修改
              let params = { id, amount, tenantTermStart, tenantTermEnd, contractUrlArray, remarks }
              let res = await this.$api.car.myParkingSpaceRentUpdate(params)
              console.log(res, '修改');
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.getTableList()
                this.mainPopShow = false
              } else {
                this.$message.error(res.message)
              }
            }


          }).catch(() => {

          });

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    deleteFileList(el) {
      this.deleteFile.push(el)
    },
    getFileList(arr) {
      this.$set(this.mainForm, 'contractUrlArray', arr)
    },
    async dow(item) {

      let soa_account = sessionStorage.getItem("soa_account");
      const token = sessionStorage.getItem("soa_token")
      axios({
        method: 'get',
        url: defaultUrl + `/business/parkingSpaceRent/downloadAnnex?filename=${item.url}`,
        headers: {
          // 在这里添加自己需要的请求头
          account: soa_account,
          token: token,
        },
        responseType: 'blob'
      }).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const a = document.createElement('a')
        a.href = url
        a.setAttribute('download', item.name)
        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)
      })

    },
    // ===================================主要弹窗



    // 选择弹窗==============================================================
    handleClick(e) {
      this.getCarSpaceData()
      console.log(e, this.activeName, 'activeName');
    },
    selectOk() { // 选择车主确认按钮
      let data = this.$refs['selectTable'].store.states.currentRow
      console.log(data, '选择确定按钮')
      if (!data) {
        this.$message.error('请先选择数据');
        return
      }
      if (this.selectType == '小区') {
        this.$set(this.mainForm, 'residentialId', data.residentialId)
        this.$set(this.mainForm, 'residentialName', data.name)
      }
      else if (this.selectType == '车位') {

        this.minTime = data.tenantTermEnd
        this.$set(this.mainForm, 'spaceId', data.spaceId)
        this.$set(this.mainForm, 'carSpaceName', data.code)
        this.$set(this.mainForm, 'ownerName', data.belongUserName)
        if (data.tenantUserId) { //如果有租赁人信息，那么就直接设置租赁人
          this.$set(this.mainForm, 'tenantUserId', data.tenantUserId)
        } else {
          this.$set(this.mainForm, 'tenantUserId', '')
        }
        if (data.tenantUserName) {
          this.$set(this.mainForm, 'tenantUserName', data.tenantUserName)
        } else {
          this.$set(this.mainForm, 'tenantUserName', '')
        }
      }
      else if (this.selectType == '租赁人') {
        this.$set(this.mainForm, 'tenantUserId', data.belongUserId)
        this.$set(this.mainForm, 'tenantUserName', data.customerName)
      }

      this.$nextTick(() => {
        this.$refs.mainForm.clearValidate()
      })


      // 获取当前表格选中项 this.$refs['selectTable'].store.states.currentRow

      // if (this.$refs['selectTable'].store.states.currentRow) {
      //    ???? = this.$refs['selectTable'].store.states.currentRow
      // }
      this.selectShow = false
    },
    // =================================================================选择弹窗

    // 列表 =====================================================================
    PageChange(e) {//分页器——页数变化
      this.pageNum = e
      this.getTableList()
    },
    pageSizeChange(e) { //分页器——每页数量变化
      this.pageNum = 1
      this.pageSize = e
      this.getTableList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getTableList()
    },
    reset() {
      this.pageNum = 1
      this.key1 = ''
      this.key2 = ''
      this.key3 = ''
      this.key4 = ''
      this.keyTime = ['', '']
      this.getTableList()
    },
    //按条件查询菜单列表
    async getTableList() {
      if (!this.keyTime) { this.keyTime = ['', ''] }
      let res = await this.$api.car.myParkingSpaceRentList({
        "residentialName": this.key1, //小区名
        "code": this.key2, //车位号
        "belongUserName": this.key3, //归属人名
        "tenantUserName": this.key4, //租赁人名
        "start": this.keyTime[0], //开始时间  格式："2024-07-09"
        "end": this.keyTime[0], //结束时间
        "pageSize": this.pageSize,
        "pageNum": this.pageNum
      })
      if (res.code == 200) {
        if (res.data.list.length == 0 && this.pageNum != 1) {
          this.pageNum = 1
          this.getTableList()
          return
        }
        this.TableData = res.data.list;
        this.totalSize = res.data.total;
      } else {
        this.$message.error(res.message)
      }

    },
    // ======================================================================列表

  },


};
</script>
<style scoped lang="less">
.htmbBox {
  display: flex;

  >div {
    &:nth-child(1) {
      width: 30%;
    }

    &:nth-child(2) {
      flex: 1;

      .htmbBox_list {
        width: 100%;

        .el {
          width: 100%;
          display: flex;
          justify-content: space-between;
          margin-bottom: 15px;
        }
      }
    }
  }
}

.tableBox {
  margin-top: 100px;

  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #fafafa;
      }
    }
  }
}

.popTableStyle {
  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 20px;

    .el-dialog__body {
      padding: 0 20px;

      .el-divider {
        margin: 20px 0;
      }
    }
  }
}

.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {

      // border-left: 1px solid #aaa;
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}



.Top {
  position: relative;

}
</style>
